<template>
  <div class="recipe-favorites">
    <div class="page-header">
      <h2>我的收藏</h2>
      <el-button 
        type="primary" 
        :icon="Plus"
        @click="showAddDialog = true"
      >
        添加收藏
      </el-button>
    </div>

    <div class="recipe-list" v-loading="loading">
      <el-empty v-if="!favorites?.length" description="暂无收藏的食谱" />
      
      <el-row :gutter="20">
        <el-col 
          v-for="recipe in favorites || []" 
          :key="recipe.recipeId"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="recipe-card" shadow="hover">
            <el-image
              :src="recipe.imageUrl"
              fit="cover"
              class="recipe-image"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>

            <div class="recipe-info">
              <h3 class="recipe-name">{{ recipe.name }}</h3>
              <div class="recipe-stats">
                <span>
                  <el-icon><Timer /></el-icon>
                  {{ recipe.cookingTime }}分钟
                </span>
                <span>
                  <el-icon><Star /></el-icon>
                  {{ recipe.calories }}千卡
                </span>
              </div>
              <p class="recipe-description">{{ recipe.description }}</p>
            </div>

            <div class="recipe-actions">
              <el-button 
                type="primary" 
                text
                @click="viewRecipe(recipe.recipeId)"
              >
                查看详情
              </el-button>
              <el-button
                type="danger"
                text
                @click="handleUnfavorite(recipe.recipeId)"
              >
                取消收藏
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-dialog
      v-model="showAddDialog"
      title="添加收藏"
      width="800px"
    >
      <div class="recipe-select" v-loading="recipeLoading">
        <el-row :gutter="20">
          <el-col 
            v-for="recipe in recipes" 
            :key="recipe.recipeId"
            :xs="24"
            :sm="12"
          >
            <el-card 
              class="recipe-item" 
              shadow="hover"
              :class="{ 'is-favorite': recipe.favorite }"
            >
              <div class="recipe-content">
                <el-image
                  :src="recipe.imageUrl"
                  fit="cover"
                  class="recipe-image"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="recipe-info">
                  <h4>{{ recipe.name }}</h4>
                  <div class="recipe-stats">
                    <span>
                      <el-icon><Timer /></el-icon>
                      {{ recipe.cookingTime }}分钟
                    </span>
                    <span>
                      <el-icon><Star /></el-icon>
                      {{ recipe.calories }}千卡
                    </span>
                  </div>
                </div>
                <el-button
                  :type="recipe.favorite ? 'danger' : 'primary'"
                  :icon="recipe.favorite ? Delete : Plus"
                  circle
                  class="favorite-btn"
                  :loading="recipe.favoriteLoading"
                  @click="handleFavorite(recipe)"
                />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Timer, Star, Plus, Delete } from '@element-plus/icons-vue'
import { getFavorites, removeFavorite, getRecipes, addFavorite } from '@/api/recipe'

const router = useRouter()
const loading = ref(false)
const favorites = ref([])
const userId = localStorage.getItem('userId')

const showAddDialog = ref(false)
const recipeLoading = ref(false)
const recipes = ref([])

// 获取收藏列表
const fetchFavorites = async () => {
  loading.value = true
  try {
    if (!userId) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    const response = await getFavorites({
      userId: parseInt(userId)
    })
    console.log('收藏列表响应:', response)
    if (response?.success) {
      favorites.value = response.data || []
    } else {
      favorites.value = []
      ElMessage.warning(response?.message || '获取收藏列表失败')
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
    favorites.value = []
  } finally {
    loading.value = false
  }
}

// 查看食谱详情
const viewRecipe = (id) => {
  router.push(`/recipes/${id}`)
}

// 取消收藏
const handleUnfavorite = async (recipeId) => {
  try {
    if (!userId) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    await ElMessageBox.confirm('确定要取消收藏这个食谱吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await removeFavorite(recipeId, { userId: parseInt(userId) })
    ElMessage.success('取消收藏成功')
    await fetchFavorites()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error)
      ElMessage.error('取消收藏失败')
    }
  }
}

// 获取食谱列表
const fetchRecipes = async () => {
  recipeLoading.value = true
  try {
    const response = await getRecipes({ userId: parseInt(userId) })
    if (response?.success) {
      recipes.value = (response.data || []).map(recipe => ({
        ...recipe,
        favoriteLoading: false
      }))
    } else {
      recipes.value = []
      ElMessage.warning(response?.message || '获取食谱列表失败')
    }
  } catch (error) {
    console.error('获取食谱列表失败:', error)
    ElMessage.error('获取食谱列表失败')
    recipes.value = []
  } finally {
    recipeLoading.value = false
  }
}

// 处理收藏/取消收藏
const handleFavorite = async (recipe) => {
  try {
    if (!userId) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
 
    recipe.favoriteLoading = true
 
    if (recipe.favorite) {
      await removeFavorite(recipe.recipeId, { userId: parseInt(userId) })
      ElMessage.success('取消收藏成功')
    } else {
      const response = await addFavorite(recipe.recipeId, { userId: parseInt(userId) })
      if (!response?.success) {
        throw new Error(response?.message || '收藏失败')
      }
      ElMessage.success('收藏成功')
    }
    
    // 更新食谱的收藏状态
    recipe.favorite = !recipe.favorite
    // 刷新收藏列表
    await fetchFavorites()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || (recipe.favorite ? '取消收藏失败' : '收藏失败'))
  } finally {
    recipe.favoriteLoading = false
  }
}

// 监听弹窗打开
watch(showAddDialog, (val) => {
  if (val) {
    fetchRecipes()
  }
})

onMounted(() => {
  fetchFavorites()
})
</script>

<style lang="scss" scoped>
.recipe-favorites {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
    }

    .el-input {
      width: 300px;
    }
  }

  .recipe-list {
    margin-bottom: 20px;
  }

  .recipe-card {
    margin-bottom: 20px;
    transition: transform 0.3s;

    &:hover {
      transform: translateY(-5px);
    }

    .recipe-image {
      width: 100%;
      height: 200px;
      border-radius: 4px;
      overflow: hidden;
    }

    .image-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: var(--el-fill-color-light);
      color: var(--el-text-color-secondary);
      font-size: 24px;
    }

    .recipe-info {
      padding: 12px 0;

      .recipe-name {
        margin: 0 0 8px;
        font-size: 16px;
        font-weight: bold;
      }

      .recipe-stats {
        display: flex;
        gap: 16px;
        color: var(--el-text-color-secondary);
        font-size: 14px;
        margin-bottom: 8px;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }

      .recipe-description {
        margin: 0;
        font-size: 14px;
        color: var(--el-text-color-regular);
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }

    .recipe-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      padding-top: 12px;
      border-top: 1px solid var(--el-border-color-lighter);
    }
  }

  .el-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .recipe-select {
    max-height: 60vh;
    overflow-y: auto;
    padding: 0 10px;

    .recipe-item {
      margin-bottom: 20px;
      transition: all 0.3s;

      &.is-favorite {
        border-color: var(--el-color-danger);
      }

      .recipe-content {
        display: flex;
        align-items: center;
        gap: 12px;
        position: relative;
      }

      .recipe-image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
        flex-shrink: 0;
      }

      .recipe-info {
        flex: 1;
        min-width: 0;

        h4 {
          margin: 0 0 8px;
          font-size: 14px;
        }

        .recipe-stats {
          display: flex;
          gap: 12px;
          font-size: 12px;
          color: var(--el-text-color-secondary);

          span {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }

      .favorite-btn {
        flex-shrink: 0;
      }
    }
  }
}

@media (max-width: 768px) {
  .recipe-favorites {
    padding: 10px;

    .page-header {
      flex-direction: column;
      gap: 10px;

      .el-input {
        width: 100%;
      }
    }
  }
}
</style> 